package com.ygqh.baby.service.task.impl;

import com.ygqh.baby.model.UserMemberModel;
import com.ygqh.baby.service.SmsService;
import com.ygqh.baby.service.YgTaskTimeService;
import com.ygqh.baby.service.YgUserMemberService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.service.task.YgUserTaskService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.MailUtil;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: sunshuo
 * @date: 2019/1/15 18:20
 */
@Service
public class YgUserTaskServiceImpl implements YgUserTaskService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private YgUserMemberService ygUserMemberService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private YgTaskTimeService ygTaskTimeService;
    @Autowired
    private MailUtil mailUtil;

    @Override
    public void checkVipUserValid() {
        Date currentDate = DateConvertUtils.getDateStart(new Date());
        String remark;
        try {
            String currentDateDesc = DateConvertUtils.format(currentDate);
            logger.info("【女王有效期审查】开始执行 --> 执行日期：" + currentDateDesc);

            // 过期女王
            List<UserMemberModel> userListByExpire = ygUserMemberService.findUserByEndDate(null, currentDate);
            doUserBusinessByExpire(userListByExpire);

            // 5天后到期的女王
            Date minDate = DateConvertUtils.addDay(currentDate, 5);
            List<UserMemberModel> userListByComingsoon =
                    ygUserMemberService.findUserByEndDate(minDate, DateConvertUtils.addDay(minDate, 1));
            // 发送提示短信
//            String shortUrl = WebUtils.generateShortUrl("http://m.yiigoo.com/static/1541129285.html?v=" + System.currentTimeMillis());
            this.sendMsgForVipUser(userListByComingsoon, "亲，您的壹果商城女王特权即将到期，有效期截至到"
                    + DateConvertUtils.format(minDate) + "，快去充值吧。");

            int expireCount = 0;
            if (CollectionUtils.isNotEmpty(userListByExpire)) {
                expireCount = userListByExpire.size();
            }
            int commingsoonCount = 0;
            if (CollectionUtils.isNotEmpty(userListByComingsoon)) {
                commingsoonCount = userListByComingsoon.size();
            }
            remark = "【女王有效期审查】执行成功，过期数：" + expireCount + "，提醒数：" + commingsoonCount;
            logger.info("【女王有效期审查】执行结束 --> 执行日期：" + currentDateDesc);
        } catch (Exception e) {
            remark = "【女王有效期审查】执行失败；" + ExceptionUtil.getExceptionMsg(e);
            logger.error("【女王有效期审查】执行失败；" + e.getMessage(), e);
        }
        ygTaskTimeService.saveOrUpdate("CheckVipUserValid", currentDate, remark);
    }

    private void sendMsgForVipUser(List<UserMemberModel> userList, String content) {
        if (CollectionUtils.isEmpty(userList)) {
            return;
        }
        userList.forEach(user -> {
            if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
                smsService.sendSms(user.getUserName(), String.format(content, DateConvertUtils.format(user.getEndTime())));
            }
        });
    }

    private void doUserBusinessByExpire(List<UserMemberModel> userModelList) {
        if (CollectionUtils.isEmpty(userModelList)) {
            System.out.println("【女王有效期审查】无过期女王 --> 执行日期：" + DateConvertUtils.formatDateTime(new Date()));
            return;
        }
        List<Long> userIdList = new ArrayList<>();
        userModelList.forEach(model -> {
            userIdList.add(model.getUserId());
            // 取消女王资格
            ygUserService.updateUserLevel(model.getUserId(), 1, null);
        });
        logger.info("【女王有效期审查】过期女王 --> userIdList: " + userIdList.toString());
        mailUtil.simpleSend("sunshuo@yiigoo.cn", "【女王有效期审查】", "今日过期女王：" + userIdList);

        // 发送提示短信
//        String shortUrl = WebUtils.generateShortUrl("http://m.yiigoo.com/static/1541129285.html?v=" + System.currentTimeMillis());
        this.sendMsgForVipUser(userModelList, "亲，您的壹果商城女王特权已经到期，快去充值吧。");
    }
}
